package org.atovio.coolexam.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.atovio.coolexam.entity.User;
import org.atovio.coolexam.exception.AuthenticationException;
import org.atovio.coolexam.exception.ServiceException;
import org.atovio.coolexam.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * token工具
 */
@Component
public class TokenUtil {

    @Resource
    private UserMapper userMapper;

    private static UserMapper staticUserMapper;

    @PostConstruct
    public void setStaticUserMapper() {
        staticUserMapper = this.userMapper;
    }

    /**
     * 生成token
     *
     * @param userId 用户id
     * @param sign   签名
     * @return token字符串
     */
    public static String createToken(int userId, String sign) {
        return JWT.create().withAudience(String.valueOf(userId)) // 将userId保存到token中，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 两小时后失效
                .sign(Algorithm.HMAC256(sign)); // 以password作为token的密钥
    }

    /**
     * 获取当前用户信息
     *
     * @return 当前用户
     */
    public static User getCurrentUser() {
        // 获取attributes
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (attributes != null) {
            // 如果成功获取attributes, 获取token
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("token");

            if (StrUtil.isNotBlank(token)) {
                // 如果token不为空
                int userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
                return staticUserMapper.selectByUserId(userId);
            } else {
                // 如果token为空, 抛异常
                throw new AuthenticationException("用户权限不足，请登录");
            }
        } else {
            // 如果没有获取到attributes, 抛个异常
            throw new ServiceException("服务器错误，获取不到Attributes");
        }
    }
}
